<template>
  <div>
    <el-card class="test">
      <div slot="header" class="title">
        <el-row :gutter="20" class="cardHeader" style="display: flex">
          <el-col style="flex: 1">
            <h4 style="margin: 0px">
              试卷信息&nbsp;&nbsp;&nbsp;{{ test.title }}
            </h4>
          </el-col>
          <el-col class="cardHeader" style="width: 250px">
            <el-button
              class="flbtn"
              v-if="!test.readonly && !isEdit"
              size="small"
              type="primary"
              @click="isEdit = true"
              >编辑</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div>
        <el-form ref="test" :rules="rules" :model="test" label-width="80px">
          <el-form-item label="试卷名称" prop="title">
            <el-input
              v-model="test.title"
              :disabled="readonly"
              placeholder="试卷名称"
            />
          </el-form-item>
          <el-form-item label="考试时长" prop="time">
            <el-input-number
              v-model="test.time"
              :disabled="readonly"
              :min="1"
              controls-position="right"
              label="考试时长"
            />
          </el-form-item>
          <el-form-item label="试卷总分" prop="score">
            <el-input-number
              v-model="test.score"
              :disabled="readonly"
              :min="1"
              controls-position="right"
              label="试卷总分"
            />
          </el-form-item>
          <el-form-item label="试卷归属">
            <el-radio-group :disabled="readonly" v-model="classTest.type">
              <el-radio :label="1">班级</el-radio>
              <el-radio :label="2">课程</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="classTest.type == 1" label="班级">
            <el-select
              filterable
              multiple
              :disabled="readonly"
              v-model="classTest.typeId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in classList"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else label="课程">
            <el-select
              filterable
              multiple
              :disabled="readonly"
              v-model="classTest.typeId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in curriculumList"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!readonly">
            <el-button type="info" @click="saveTest()">
              <span v-if="test.id === null">立即创建</span>
              <span v-else>暂存</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card v-if="test.id !== null" class="test">
      <div slot="header" class="clearfix">
        <span>试卷结构(注*支持拖拽排序)</span>
      </div>
      <div class="draggable">
        <draggable
          :disabled="readonly"
          v-model="testStructures"
          style="display: inline-block"
          @update="updateSort"
        >
          <el-tag
            @click="editTestStructures(structure)"
            @close="handleClose(structure)"
            closable
            v-for="structure in testStructures"
            :key="structure.questionSetId"
            >{{ structure.title }}({{ structure.score }}分)</el-tag
          >
        </draggable>
      </div>
      <div v-if="inputVisible && !readonly" class="addStructure">
        <el-input
          v-model="testStructure.title"
          placeholder="标题"
          class="input-new-tag"
          size="small"
        />
        <el-input-number
          v-model="testStructure.score"
          :min="1"
          :max="100"
          size="small"
          placeholder="分数"
        />
        <el-button
          size="small"
          type="info"
          class="button-new-tag"
          @click="saveStructure"
          >保存</el-button
        >
        <el-button size="small" class="button-new-tag" @click="close"
          >取消</el-button
        >
      </div>
      <el-button
        v-else-if="!readonly"
        class="button-new-tag"
        size="small"
        @click="inputVisible = true"
        >+ New</el-button
      >
    </el-card>
    <div class="test">
      <el-row :gutter="50">
        <el-col :span="16">
          <el-card
            v-for="structure in testStructures"
            :key="structure.questionSetId"
            class="structure"
          >
            <div slot="header" class="clearfix">
              <el-row :gutter="24">
                <el-col :span="16">
                  <span class="structureTitle">
                    {{ structure.title }}({{ structure.score }}分)
                    <span>(注*支持拖拽排序)</span>
                  </span>
                </el-col>
                <el-col :span="8">
                  <el-button
                    v-if="!readonly"
                    class="button-new-tag"
                    size="small"
                  >
                    <router-link
                      :to="{
                        name: 'TestQuestionInfo',
                        params: {
                          test: {
                            id: test.id,
                            title: test.title,
                            year: test.year,
                            testStructures: testStructures,
                            testStructure: structure.id,
                          },
                        },
                      }"
                      >添加题目</router-link
                    >
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <draggable
              :disabled="readonly"
              v-model="structure.question"
              @update="updateSortQuestion($event, structure)"
            >
              <el-card
                class="questionItem"
                :key="question.id"
                v-for="(question, index) in structure.question"
              >
                <el-row>
                  <el-col :span="2">题目:</el-col>
                  <el-col :span="1">{{ index + 1 }}</el-col>
                  <el-col :span="1" class="fg">|</el-col>
                  <el-col :span="6">
                    <span class="questionTitle" v-html="question.title"></span>
                  </el-col>
                  <el-col :span="2">
                    <el-tag effect="dark" size="mini">{{
                      questionType[question.type]
                    }}</el-tag>
                  </el-col>
                  <el-col :span="1" class="fg">|</el-col>
                  <el-col :span="2">
                    <el-tag size="mini" :type="question | tag">{{
                      question | status
                    }}</el-tag>
                  </el-col>
                  <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                  <el-col v-if="!readonly" :span="2">
                    <el-link icon="el-icon-edit">
                      <router-link
                        :to="{
                          name: 'TestQuestionInfo',
                          params: {
                            test: {
                              id: test.id,
                              title: test.title,
                              year: test.year,
                              testStructures: testStructures,
                              testStructure: structure.id,
                            },
                            question: {
                              id: question.questionId,
                              score: question.score,
                            },
                          },
                        }"
                        >编辑</router-link
                      >
                    </el-link>
                  </el-col>
                  <el-col :span="1" class="fg">|</el-col>
                  <el-col :span="2">
                    <el-link
                      icon="el-icon-view"
                      @click="show(question.questionId)"
                      >预览</el-link
                    >
                  </el-col>
                  <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                  <el-col v-if="!readonly" :span="2">
                    <el-link
                      icon="el-icon-delete"
                      type="danger"
                      @click="
                        deleteTestQuestion(structure.id, question.questionId)
                      "
                      >删除</el-link
                    >
                  </el-col>
                </el-row>
              </el-card>
            </draggable>
          </el-card>
        </el-col>
        <el-col v-if="testStructures.length > 0" :span="8">
          <Sticky>
            <el-card class="phoneShow">
              <div class="phoneContent">
                <phone :question="question" />
              </div>
            </el-card>
          </Sticky>
        </el-col>
      </el-row>
    </div>
    <select-question
      :dialogVisible.sync="dialogVisible"
      :questionIds.sync="questionIds"
      :isScore="true"
      v-on:selectQuestion="selectQuestion"
    ></select-question>
  </div>
</template>

<script>
import Sticky from "@/components/Sticky";
import draggable from "vuedraggable";
import MDinput from "@/components/MDinput";
import { getAreaList } from "@/api/area.js";
import { getDictionary } from "@/api/dictionary.js";
import { getSubjectTypeList } from "@/api/subjectType.js";
import { getTestTypeList } from "@/api/testType.js";
import {
  addQuestionToTest,
  bindClassOrCurriculum,
  getClassOrCurriculum,
} from "@/api/test.js";
import { getTeacher } from "@/api/teacher.js";
import { getClassList, getCurriculumList } from "@/api/clazz.js";
import phone from "@/components/phone";
import {
  addUpTest,
  testInfo,
  commitCheck,
  rejectCheck,
  commitReview,
  rejectReview,
  review,
  questionSort,
  deleteTestQuestion,
} from "@/api/test.js";
import {
  saveTestStructure,
  getTestStructure,
  deleteTestStructure,
  testStructureSort,
} from "@/api/testStructure.js";
import SelectTeacher from "@/views/test/components/SelectTeacher";
import SelectQuestion from "@/views/test/components/SelectQuestion";
import Msg from "@/views/test/components/Msg";
import { questionInfo } from "@/api/question.js";

export default {
  name: "TestInfo",
  components: {
    MDinput,
    draggable,
    SelectTeacher,
    phone,
    Sticky,
    Msg,
    SelectQuestion,
  },
  filters: {
    tag(row) {
      if (row.status === 1) {
        return "success";
      }
      if (row.editStatus !== 1) {
        return "info";
      }
      if (row.checkStatus !== 1) {
        return "warning";
      }
      if (row.reviewStatus === 1) {
        return "success";
      }
      return "";
    },
    status(row) {
      if (row.status === 1) {
        return "上线";
      }
      if (row.status === 0) {
        return "编辑中";
      }
      if (row.status == 3) {
        return "校验中";
      }
      if (row.status == 4) {
        return "审核中";
      }
      if (row.status == 5) {
        return "已审核";
      }
      return "下线";
    },
  },
  data() {
    return {
      rules: {
        title: [{ required: true, message: "试卷名称必填", trigger: "blur" }],
        time: [{ required: true, message: "考试时间必填", trigger: "blur" }],
        score: [{ required: true, message: "考试分数必填", trigger: "blur" }],
      },
      classTest: {
        type: 1,
      },
      question: {},
      questionType: {
        1: "选择题",
        2: "多选题",
        3: "判断题",
        4: "情景题",
        5: "简答题",
        6: "辨析题",
        7: "填空",
        8: "完形填空",
        9: "阅读理解",
        10: "背景题",
      },
      isEdit: false,
      teacher: [],
      testType: [],
      areaList: [],
      schoolSections: [],
      subjectTypes: [],
      testArea: 0,
      testStructures: [],
      test: {
        id: null,
        title: "",
        testArea: [[0]],
        testSubject: [],
        testSchoolSection: [],
        type: 1,
        dataType: 1,
        readonly: true,
      },
      inputVisible: false,
      testStructure: {
        title: "",
        score: 0,
      },
      dialogVisible: false,
      questionIds: [],
      selectQuestionTestId: 0,
      selectQuestionTestStructureId: 0,
      classList: [],
      curriculumList: [],
    };
  },
  computed: {
    readonly: function () {
      return (!this.isEdit || this.test.readonly) && this.test.id != null;
    },
    isCommit: function () {
      return this.$store.getters.role === 2 && this.testStructures.length > 0;
    },
  },
  created() {
    this.getArea();
    this.getTestType();
    this.getSubjectType();
    this.getSchoolSections();
    this.getTestInfo();
    getClassList().then((res) => {
      this.classList = res.data;
    });
    getCurriculumList().then((res) => {
      this.curriculumList = res.data;
    });
    if (this.test.id) {
      getClassOrCurriculum(this.test.id).then((res) => {
        res = res.data;
        this.classTest.type =res.length>0? parseInt(res[0].value):1;
        console.log( this.classTest.type)
        this.classTest.typeId =res.length>0? res.map(item=>item.label):[];
      });
    }
  },
  methods: {
    close() {
      this.getTestStructureList();
      this.testStructure = {
        title: "",
        score: 0,
      };
      this.inputVisible = false;
    },
    editTestStructures(testStructures) {
      this.testStructure = testStructures;
      this.inputVisible = true;
    },
    deleteTestQuestion(structureId, id) {
      deleteTestQuestion(this.test.id, structureId, id).then(() => {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getTestStructureList();
      });
    },
    show(id) {
      questionInfo(id).then((res) => {
        let data = res.data;
        if (data.answer) {
          data.answer = JSON.parse(data.answer);
        }
        this.question = res.data;
      });
    },

    getTestStructureList() {
      getTestStructure(this.test.id).then((res) => {
        this.testStructures = res.data;
      });
    },
    getTeacherList(status) {
      getTeacher(status).then((res) => {
        this.teacher = res.data.filter(
          (teacher) => this.$store.getters.name != teacher.name
        );
        if (this.teacher && !this.test.checkPeople) {
          this.test.checkPeople = this.teacher[0].id;
        }
        if (this.teacher && !this.test.reviewPeople) {
          this.test.reviewPeople = this.teacher[0].id;
        }
      });
    },
    getTestInfo() {
      const id = this.test.id || this.$router.currentRoute.query.id;
      if (id) {
        this.test.id = id;
        testInfo(id).then((res) => {
          this.test = res.data;
          if (this.test.checkPeople === 0) {
            this.test.checkPeople = null;
          }
          if (this.test.reviewPeople === 0) {
            this.test.reviewPeople = null;
          }
          if (res.data.testArea && res.data.testArea[0][0] != 0) {
            this.testArea = -1;
          }
          this.getTeacherList(res.data.status);
          this.getTestStructureList();
        });
      }
    },
    saveTest() {
      if (!this.classTest.typeId) {
        this.$message.error("请选择关联的班级或者课程");
        return;
      }
      this.$refs["test"].validate((valid) => {
        if (valid) {
          this.test.isNew = 3;
          addUpTest(this.test).then((res) => {
            let values = this.classTest.typeId.map((item) => {
              return {
                label: this.classTest.type + "",
                value: item + "",
              };
            });
            bindClassOrCurriculum(res.data.id, values).then((ret) => {
              this.test.id = res.data.id;
              this.$message.success("更新成功!");
              this.getTestInfo();
              this.isEdit = false;
            });
          });
        } else {
          return false;
        }
      });
    },
    saveStructure() {
      this.inputVisible = false;
      if (this.testStructure.title && this.testStructure !== 0) {
        saveTestStructure(this.testStructure, this.test.id).then((res) => {
          this.getTestStructureList();
          this.testStructure = {
            title: "",
            score: 0,
          };
        });
      }
    },
    handleClose(tag) {
      console.log(tag);
      deleteTestStructure(this.test.id, tag.id).then((res) =>
        this.getTestStructureList()
      );
    },
    updateSortQuestion(evt, structure) {
      const questions = structure.question;
      const changeTags = questions[evt.newIndex];
      let sort;
      let beforeSort;
      let afterSort;
      if (evt.newIndex === 0) {
        beforeSort = questions[evt.newIndex + 1].sort - 50;
      } else {
        beforeSort = questions[evt.newIndex - 1].sort;
      }
      if (evt.newIndex === questions.length - 1) {
        afterSort = questions[evt.newIndex - 1].sort + 50;
      } else {
        afterSort = questions[evt.newIndex + 1].sort;
      }
      sort =
        Math.floor(Math.random() * (afterSort - beforeSort + 1)) + beforeSort;
      questionSort(
        this.test.id,
        structure.id,
        changeTags.questionId,
        sort
      ).then((res) => this.getTestStructureList());
    },
    updateSort(evt) {
      const changeTags = this.testStructures[evt.newIndex];
      let sort;
      let beforeSort;
      let afterSort;
      if (evt.newIndex === 0) {
        beforeSort = this.testStructures[evt.newIndex + 1].sort - 50;
      } else {
        beforeSort = this.testStructures[evt.newIndex - 1].sort;
      }
      if (evt.newIndex === this.testStructures.length - 1) {
        afterSort = this.testStructures[evt.newIndex - 1].sort + 50;
      } else {
        afterSort = this.testStructures[evt.newIndex + 1].sort;
      }
      sort =
        Math.floor(Math.random() * (afterSort - beforeSort + 1)) + beforeSort;
      testStructureSort(this.test.id, changeTags.id, sort).then((res) =>
        this.getTestStructureList()
      );
    },
    getArea() {
      getAreaList().then((res) => (this.areaList = this.getTreeData(res.data)));
    },
    getSubjectType() {
      getSubjectTypeList().then((res) => (this.subjectTypes = res.data));
    },
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    openSelectQuestion(testId, testStructureId) {
      this.selectQuestionTestId = testId;
      this.selectQuestionTestStructureId = testStructureId;
      this.dialogVisible = true;
    },
    selectQuestion() {
      if (this.questionIds.length > 0) {
        for (let index = 0; index < this.questionIds.length; index++) {
          addQuestionToTest(
            this.selectQuestionTestId,
            this.selectQuestionTestStructureId,
            this.questionIds[index].id,
            this.questionIds[index].score
          ).then((res) => {
            if (index == this.questionIds.length - 1) {
              this.$message.success("导入题目成功!");
              this.getTestStructureList();
            }
          });
        }
      }
    },
  },
};
</script>
<style>
.questionItem .el-card__body {
  padding: 12px;
}
.questionTitle p {
  margin: 0px;
}
</style>
<style rel="stylesheet/scss" lang="scss"scoped>
.test {
  width: 90%;
  margin-left: 5%;
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.structureTitle {
  line-height: 32px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.addStructure {
  display: inline-block;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.draggable {
  display: inline-block;
}
.questionItem {
  margin-top: 5px;
  font-size: 15px;
  text-align: center;
}

.fg {
  color: #e4e7ed;
}
.phoneShow {
  width: 400px;
  margin-top: 5px;
}
.phoneContent {
  margin: 0px auto;
  width: 320px;
}
.structure {
  margin-top: 5px;
}
</style>
